﻿using MKAdmin.Web.App_Start;
using MKAdmin.IService;
using Ninject;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MKAdmin.Web.Controllers;
using MKAdmin.DTO.Web.Common;
using MKAdmin.Web.Authorizes;
using System.Web.Security;
using MKAdmin.ToolKit.FileKit;
using System.IO;

namespace MKAdmin.Web.Controllers
{
    public class HomeController : BaseMvcController
    {
        [Inject]
        public ITest Test { set; get; }

        public ActionResult Index()
        {
            UserInfoModel userInfo = CurrentUser.GetLoginInfo();
            return View(PageViewFilesConfig.Home, userInfo);
        }

        public ActionResult Welcome()
        {
            return View(PageViewFilesConfig.Welcome);
        }

        public ActionResult GroupMgrIndex()
        {
            return View(PageViewFilesConfig.BasicTableIndex);
        }

        /// <summary>
        /// 上传文件处理
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public ContentResult UploadFile()
        {
            HttpFileCollectionBase files = HttpContext.Request.Files;
            Result<UploadFileModel> model = new Result<UploadFileModel>();
            if (files != null && files.Count > 0)
            {
                HttpPostedFileBase uploadFileData = files[0];

                model.status = false;
                if (Request.Form["uploadfile_ant"] == null)
                {
                    model.msg = "请设置参数：ant, 参照web.config中 FileKit->Catalog->Key的值！";
                    return Content(Newtonsoft.Json.JsonConvert.SerializeObject(model));
                }
                string key = Request.Form["uploadfile_ant"].ToString();
                var catalogConfig = FileCatalogHelper.Catalog[key];

                model.data = new UploadFileModel();
                model.data.originalName = uploadFileData.FileName;
                string extenName = Path.GetExtension(model.data.originalName);
                if (catalogConfig.FileTypeLimit.ToUpper().IndexOf(extenName.ToUpper()) < 0)
                {
                    model.msg = string.Format("请上传文件格式：{0} ！", catalogConfig.FileTypeLimit);
                    return Content(Newtonsoft.Json.JsonConvert.SerializeObject(model));
                }

                int fileSizeMax = int.Parse(catalogConfig.FileSize) * 1024 * 1024;
                model.data.fileSize = uploadFileData.ContentLength;
                if (model.data.fileSize > fileSizeMax)
                {
                    model.msg = string.Format("上传文件必须小于等于 {0}MB", catalogConfig.FileSize);
                    return Content(Newtonsoft.Json.JsonConvert.SerializeObject(model));
                }

                model.data.catalog = $@"/{DateTime.Now.ToString("yyyyMM")}/{DateTime.Now.ToString("yyyyMMdd")}";
                string filePath = $@"{catalogConfig.TempFile.AbsolutePath}{model.data.catalog.Replace("/", "\\")}";
                if (!Directory.Exists(filePath))
                    Directory.CreateDirectory(filePath);

                string guid = Guid.NewGuid().ToString("N");
                model.data.fileName = string.Format("{0}{1}", guid, extenName);
                filePath = Path.Combine(filePath, model.data.fileName);
                uploadFileData.SaveAs(filePath);
                model.data.url = string.Format("{0}/{1}/{2}", catalogConfig.TempFile.RelativePath
                    , model.data.catalog, model.data.fileName);

                model.status = true;
                model.msg = "成功！";
            }
            else
            {
                model.msg = "请选择文件";
            }
            return Content(Newtonsoft.Json.JsonConvert.SerializeObject(model));
        }

        /// <summary>
        /// 下载本地文件
        /// </summary>
        /// <param name="fileName">文件名:(eg:Files/用户信息模板.xlsx)</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult DownLoadFile(string fileName)
        {
            string filePath = HttpContext.Server.MapPath(fileName);
            string downLoadFileName = Path.GetFileName(fileName);

            return File(filePath, MimeMapping.GetMimeMapping(filePath), downLoadFileName);
        }

        /// <summary>
        /// 下载配置文件配置好的文件
        /// </summary>
        /// <param name="catalog"></param>
        /// <param name="fileName"></param>
        /// <param name="type">0:临时目录,1:正式目录</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult DownLoadConfigFile(string key, string catalog, string fileName, int type)
        {
            var catalogConfig = FileCatalogHelper.Catalog[key];

            string filePath = $@"{catalogConfig.TempFile.AbsolutePath}{catalog}\{fileName}";
            if (type == 1)
            {
                filePath = $@"{catalogConfig.DestFile.AbsolutePath}{catalog}\{fileName}";
            }
            string downLoadFileName = Path.GetFileName(fileName);

            return File(filePath, MimeMapping.GetMimeMapping(filePath), downLoadFileName);
        }

        [HttpGet]
        public ActionResult SignOut()
        {
            Loginer.SignOut();
            return Redirect(FormsAuthentication.LoginUrl);
        }
    }
}